package com.xcj.juhe.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xcj.juhe.dto.OrderDto;
import com.xcj.juhe.mapper.test1.OrderMapper;
import com.xcj.juhe.mapper.test1.UserMapper;
import com.xcj.juhe.service.OrderService;
import com.xcj.juhe.tool.MyTool;
import com.xcj.juhe.vo.OrderStatusVO;
import com.xcj.juhe.vo.OrderVO;
import com.xcj.juhe.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;

/**
 * @author xcj
 * @date 2021/5/10 19:19
 */
@Slf4j
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private UserMapper userMapper;

    private static String URL = "http://test-api.gamedachen.com/order/create";

    MyTool myTool = new MyTool();

    @Override
    public ResultVO addOrder(ArrayList<OrderDto> orderDtos) {


        ResultVO resultVO = new ResultVO();

        Map map = new HashMap();
        ArrayList list = new ArrayList();
        int sum = 0;

        for (OrderDto orderDto : orderDtos) {
            for (int i = 0; i < orderDto.getRoleIds().size(); i++) {
                OrderVO orderVO = orderMapper.selectOrderVoByRoleId(orderDto.getRoleIds().get(i), orderDto.getChannelId());
                if (orderVO != null) {
                    String timeStr = myTool.StringToTime(orderDto.getTime());

                    map.put("userId", orderVO.getUserId());
                    map.put("roleName", orderVO.getRoleName());
                    map.put("serverId", orderVO.getServerId());
                    map.put("serverName", orderVO.getServerName());

                    map.put("money", orderDto.getMoney());
                    map.put("channelId", orderDto.getChannelId());
                    map.put("sdkId", orderDto.getSdkId());
                    map.put("appId", orderDto.getAppId());
                    map.put("realMoney", orderDto.getMoney());
                    map.put("roleId", orderDto.getRoleIds().get(i));

                    map.put("productId", "商品id");
                    map.put("productDesc", "商品描述");
                    map.put("productName", "商品名称");
                    map.put("roleLevel", "1");
                    map.put("signType", "MD5");
                    map.put("currency", "币种");
                    map.put("notifyUrl", "1");

                    map.put("cpOrderId", "cp_" + System.currentTimeMillis() + "" + new Random().nextInt(100));
                    if (Integer.parseInt(timeStr) > Integer.parseInt(userMapper.selectUserRegTimeByUserId(orderVO.getUserId()))){
                        String mintSdkOrderId = this.callOrder(map);
                        //如果下单成功就更新订单信息
                        if (mintSdkOrderId != null) {
                            OrderStatusVO orderStatusVO = new OrderStatusVO();
                            orderStatusVO.setOrderId(mintSdkOrderId);
                            orderStatusVO.setStatus(orderDto.getState());
                            long completeTime = Long.parseLong(timeStr);
                            orderStatusVO.setTime(String.valueOf(completeTime));
                            if (this.updateOrderInfoByOrederId(orderStatusVO)) {
                                log.info("更新订单{}状态成功", mintSdkOrderId);
                                list.add(mintSdkOrderId);
                                sum++;
                            } else {
                                log.error("虽然{}下单成功，但是更新订单状态失败", mintSdkOrderId);
                            }
                        }
                    }else {
                        log.error("订单完成时间不能在用户注册时间之前");
                    }

                } else {
                    log.error("查无角色{}信息，下单失败", orderDto.getRoleIds().get(i));
                }
            }

            if (sum > 0) {
                resultVO.setCode(200);
                resultVO.setMsg("success");
                Map resultMap = new HashMap();
                resultMap.put("number", sum);
                resultMap.put("orderData", list);
                resultVO.setData(resultMap);
            } else {
                resultVO.setCode(100);
                resultVO.setMsg("都下单失败");
            }
        }
        return resultVO;
    }

    /**
     * 更新订单状态和完成时间
     *
     * @param orderStatusVO
     * @return
     */
    private Boolean updateOrderInfoByOrederId(OrderStatusVO orderStatusVO) {

        int i = orderMapper.updateOrderInfoByOrderId(orderStatusVO.getOrderId(), orderStatusVO.getStatus(), orderStatusVO.getTime());
        if (i > 0) {
            return true;
        }
        return false;
    }

    private String callOrder(Map map) {

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> request = new HttpEntity<Map<String, Object>>(map, headers);

        ResponseEntity<String> entity = restTemplate.postForEntity(URL, request, String.class);

        String body = entity.getBody();

        log.info("{}下单了，接口响应：{}", map.get("roleId"), body);

        JSONObject json = JSON.parseObject(body);
        String code = json.getString("code");

        if (code.equals("200")) {
            return json.getString("data");
        } else {
            log.error("下单失败:{}", body);
            return null;
        }

    }

}
